package beautiful.butterfly.server.httpserver.mvc.handler;


import beautiful.butterfly.server.httpserver.mvc.core.ActionContext;
import beautiful.butterfly.server.httpserver.mvc.http.Request;
import beautiful.butterfly.server.httpserver.mvc.http.Response;
import beautiful.butterfly.server.httpserver.mvc.render.TextRender;

import java.io.PrintWriter;
import java.io.StringWriter;

import static beautiful.butterfly.server.httpserver.mvc.Constant.INTERNAL_SERVER_ERROR_HTML;


public class DefaultExceptionHandler implements ExceptionHandler {

    @Override
    public void handle(Exception e) {
        Request request = ActionContext.getRequest();
        Response response = ActionContext.getResponse();

        handleException(e, request, response);
    }


    private void handleException(Exception e, Request request, Response response) {
        e.printStackTrace();
        if (null != response) {
            response.setStatusCode(500);
            request.setAttribute("title", "500 Internal IHttpServer Error");
            request.setAttribute("message", e.getMessage());
            request.setAttribute("stackTrace", getStackTrace(e));
            this.render500(request, response);
        }
    }

    private void render500(Request request, Response response) {

        String page500 = null;
        if (page500 != null) {
            response.render(new TextRender(page500));
        } else {
            if (true) {

            } else {
                response.html(INTERNAL_SERVER_ERROR_HTML);
            }
        }
    }

    private String getStackTrace(Throwable throwable) {
        StringWriter stringWriter = new StringWriter();
        throwable.printStackTrace(new PrintWriter(stringWriter));
        return stringWriter.toString();
    }

}
